const puppeteer = require("puppeteer-core");
let fs = require("fs");
let path = require("path");
async function pc() {
  const browser = await puppeteer.launch({
    headless: false, //有浏览器界面启动
    slowMo: 100, //放慢浏览器执行速度，方便测试观察
    ignoreHTTPErrors: true,
    defaultViewport: { width: 1600, height: 700 },
    args: [
      //启动 Chrome 的参数，详见上文中的介绍
      "–no-sandbox",
      // '--start-fullscreen'
    ],
  });
  const page = await browser.newPage();
  await page.goto(
    "https://www.55128.cn/zs/12_96.htm?startTerm=2022001&endTerm=2024146"
  );

  // await page.$eval("#startTerm", (el) => (el.value = ""));
  // await page.type("#startTerm", "2022001", { delay: 100 });
  // await page.click("#btnSearch");

  //$('.test').children[1]
  // let dzj = await page.$$(".search-link span");
  // let djz3 = dzj[2];
  // await djz3?.click();
  // await page.waitForTimeout(2000);
  // let head = await page.$("thead .sort_up");
  // await head?.click();

  //let table = await page.$$("#chartData tr");
  let body = await page.$("#chartData");
  let res = await page.evaluate(function (el) {
    let trs = el.querySelectorAll("tr");
    let allBalls = {};
    trs.forEach((tr) => {
      let line = 0;
      let time = "";
      let td = tr.querySelectorAll("td");
      let red = [],
        blue = [],
        wzjred = [],
        wzjblue = [];
      td.forEach((item, index) => {
        if (index == 0) {
          time = item.innerText;
          allBalls[time] = {};
        }
        if (
          item.className.includes("chartball_red1") ||
          item.className.includes("chartball_red2")
        ) {
          //红色中奖球
          red.push(item.innerText - 0);
        } else if (item.className.includes("chartball_blue")) {
          //绿色中奖球
          blue.push(item.innerText - 0);
        } else if (item.className.includes("miss-yred") && index < 40) {
          wzjred.push(item.innerText - 0 + 1);
        } else if (item.className.includes("miss-yred-c2") && index > 40) {
          wzjblue.push(item.innerText - 0 + 1);
        }
      });
      for (let i of red) {
        wzjred.splice(i - 1, 0, 1);
      }
      for (let i of blue) {
        wzjblue.splice(i - 1, 0, 1);
      }
      allBalls[time].red = red;
      allBalls[time].blue = blue;
      allBalls[time].wzjred = wzjred; //红球所有球的权重
      allBalls[time].wzjblue = wzjblue; //蓝球所有球的权重
    });
    console.log(allBalls, "爬虫结果");
    return {
      allBalls,
    };
  }, body);
  //let clures=await page
  // await p()
  if (!fs.existsSync(path.join(__dirname, "./img"))) {
    fs.mkdirSync(path.join(__dirname, "./img"));
  }

  await page.screenshot({ path: path.join(__dirname, "./img/cp.png") });
  browser.close();
  if (!fs.existsSync(path.join(__dirname, "./res"))) {
    fs.mkdirSync(path.join(__dirname, "./res"));
  }
  fs.writeFileSync(
    path.join(__dirname, "./res", "res.json"),
    JSON.stringify(res.allBalls, null, 2)
  );

  return res;
}

// console.log(pc(), "爬虫结果");
pc();
